package com.robot.admin.controller;

import com.alibaba.fastjson.JSON;
import com.robot.admin.client.AgentClient;
import com.robot.admin.client.OrdersClient;
import com.robot.admin.dao.vo.AgentDao;
import com.robot.admin.pojo.client.Agent;
import com.robot.admin.pojo.vo.CashWithdrawal;
import com.robot.admin.service.AdminService;
import com.robot.admin.util.CastEntityUtil;
import com.robot.admin.util.SendMessageUtil;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import util.CheckUtil;
import util.UpdateUtil;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 代理商模块
 *
 * @author wuyunbin
 */
@RestController
@CrossOrigin
@RequestMapping("/agent")
public class AgentController {
    @Autowired
    private AdminService adminService;

    @Autowired
    private AgentDao agentDao;

    @Autowired
    private AgentClient agentClient;
    @Autowired
    private OrdersClient ordersClient;

    @Autowired
    private CheckUtil checkUtil;
    @Autowired
    private SendMessageUtil sendMessageUtil;
    @Autowired
    private HttpServletRequest request;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 条件查询并分页
     *
     * @param searchMap
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(value = "/search/{page}/{size}", method = RequestMethod.POST)
    public Result findAgentsBySearch(@RequestBody Map searchMap, @PathVariable int page, @PathVariable int size) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        //判断是否登录
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        logger.info("searchMap=" + searchMap);
        return new Result(StatusCode.SUCCESS_QUERY, JSON.parseObject(agentClient.thirdFindAgentsBySearch(searchMap, page, size)));
    }

    /**
     * 根据ID查询
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Result findAgentById(@PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        //判断是否登录
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        Agent agentInDb = JSON.parseObject(agentClient.thirdFindAgentById(id), Agent.class);
        logger.info("agentInDb=" + agentInDb);
        String message = checkPojo(agentInDb);
        if (!"".equals(message)) {
            return new Result(StatusCode.ERROR, message);
        }

        return new Result(StatusCode.SUCCESS_QUERY, agentInDb);
    }

    /**
     * 修改
     *
     * @param agent
     * @param id
     * @return
     */
    @RequestMapping(value = "updateAgent/{id}", method = RequestMethod.PUT)
    public Result updateAgent(@RequestBody Agent agent, @PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        //判断是否登录
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        Agent agentInDb = JSON.parseObject(agentClient.thirdFindAgentById(id), Agent.class);
        logger.info("agentInDb=" + agentInDb);
        String message = checkPojo(agentInDb);
        if (!"".equals(message)) {
            return new Result(StatusCode.ERROR, message);
        }

        logger.info("agent=" + agent);
        if (agent.getRealName() == null || "".equals(agent.getRealName())) {
            return new Result(StatusCode.ERROR_AGENT_NAME_REQUIRED);
        }
        if (!checkUtil.checkPhone(agent.getPhone())) {
            return new Result(StatusCode.ERROR_INVALID_PHONE);
        }
        if (checkUtil.checkEmail(agent.getEmail())) {
            return new Result(StatusCode.ERROR_INVALID_EMAIL);
        }
        if (agent.getBankName() == null || "".equals(agent.getBankName())) {
            return new Result(StatusCode.ERROR_BANK_REQUIRED);
        }
        if (agent.getBankAccount() == null || "".equals(agent.getBankAccount())) {
            return new Result(StatusCode.ERROR_BANK_ACCOUNT_REQUIRED);
        }
        if (agent.getAccountType() == null || "".equals(agent.getAccountType())) {
            return new Result(StatusCode.ERROR_ACCOUNT_TYPE_REQUIRED);
        }
        if (agent.getProvince() == null || "".equals(agent.getProvince()) || agent.getProvinceId() == null || "".equals(agent.getProvinceId())) {
            return new Result(StatusCode.ERROR_PROVINCE_REQUIRED);
        }
        if (agent.getCity() == null || "".equals(agent.getCity()) || agent.getCityId() == null || "".equals(agent.getCityId())) {
            return new Result(StatusCode.ERROR_CITY_REQUIRED);
        }
        if (agent.getArea() == null || "".equals(agent.getArea()) || agent.getAreaId() == null || "".equals(agent.getAreaId())) {
            return new Result(StatusCode.ERROR_AREA_REQUIRED);
        }
        if (agent.getIdCard() == null || "".equals(agent.getIdCard())) {
            return new Result(StatusCode.ERROR_ID_CARD_REQUIRED);
        }
        if (agent.getIdCardFront() == null || "".equals(agent.getIdCardFront())) {
            return new Result(StatusCode.ERROR_ID_CARD_FRONT_REQUIRED);
        }
        if (agent.getIdCardBack() == null || "".equals(agent.getIdCardBack())) {
            return new Result(StatusCode.ERROR_ID_CARD_BACK_REQUIRED);
        }

        agent.setId(agentInDb.getId());
        agent.setStatus(agentInDb.getStatus());
        agent.setRealNameStatus(agentInDb.getRealNameStatus());
        agent.setPassword(agentInDb.getPassword());
        agent.setCreatedAt(agentInDb.getCreatedAt());
        UpdateUtil.copyNonNullProperties(agent, agentInDb);
        agentInDb.setUpdatedAt(LocalDateTime.now());
        agentClient.thirdUpdateAgent(JSON.toJSONString(agentInDb));
        return new Result(StatusCode.SUCCESS_UPDATED);
    }

    /**
     * 代理商禁用/启用
     *
     * @param agent
     * @param id
     * @return
     */
    @PutMapping("firstTrial/{id}")
    public Result firstTrial(@RequestBody Agent agent, @PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        //判断是否登录
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        Agent agentInDb = JSON.parseObject(agentClient.thirdFindAgentById(id), Agent.class);
        logger.info("agentInDb=" + agentInDb);
        String message = checkPojo(agentInDb);
        if (!"".equals(message)) {
            return new Result(StatusCode.ERROR, message);
        }

        String status = agent.getStatus();
        /**
         * agent表status状态 0-禁用 1-启用
         */
        String agentStatusForbidden = "0";
        String agentStatusEnable = "1";
        if (agentStatusEnable.equals(status) || agentStatusForbidden.equals(status)) {
//            if (agentStatusEnable.equals(agentInDb.getStatus()) && agentStatusEnable.equals(status)) {
//                return new Result(false, StatusCode.ERROR, "操作失败,该代理商本来就是启用状态");
//            }
//            if (agentStatusForbidden.equals(agentInDb.getStatus()) && agentStatusForbidden.equals(status)) {
//                return new Result(false, StatusCode.ERROR, "操作失败,该代理商本来就是禁用状态");
//            }
            agentInDb.setStatus(status);
            agentClient.thirdUpdateAgent(JSON.toJSONString(agentInDb));
        } else {
            return new Result(StatusCode.ERROR, "审核状态必须是" + agentStatusForbidden + "或者" + agentStatusEnable);
        }
        return new Result(StatusCode.SUCCESS);
    }

    /**
     * 代理商软删除
     *
     * @param id
     * @return
     */
    @PutMapping("deleteAgent/{id}")
    public Result deleteAgent(@PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        //判断是否登录
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        Agent agentInDb = JSON.parseObject(agentClient.thirdFindAgentById(id), Agent.class);
        logger.info("agentInDb=" + agentInDb);
        String message = checkPojo(agentInDb);
        if (!"".equals(message)) {
            return new Result(StatusCode.ERROR, message);
        }

        agentInDb.setDeletedAt(LocalDateTime.now());
        agentClient.thirdUpdateAgent(JSON.toJSONString(agentInDb));
        return new Result(StatusCode.SUCCESS_DELETED);
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public Result delete(@PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        //判断是否登录
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        agentClient.thirdDeleteAgentById(id);
        return new Result(StatusCode.SUCCESS_DELETED);
    }

    /**
     * 消息推送
     *
     * @param map
     * @return
     */
    @PostMapping("messagePush")
    public Result sendSms(@RequestBody Map map) {
        Map<String, Object> resultMap = sendMessageUtil.sendMessage(map);
        return new Result(StatusCode.SUCCESS_SEND);
    }


    /**
     * 代理商提现管理列表
     *
     * @return
     * @throws Exception
     */
    @GetMapping("cashWithdrawal")
    public Result cashWithdrawals() throws Exception {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        //判断是否登录
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        List<CashWithdrawal> cashWithdrawals = CastEntityUtil.castEntity(agentDao.findCashWithdrawals(), CashWithdrawal.class);
        return new Result(StatusCode.SUCCESS_QUERY, cashWithdrawals);
    }

    /**
     * 代理商提现管理明细
     *
     * @param agentId
     * @param createdAt
     * @param page
     * @param size
     * @return
     */
    @GetMapping("cashWithdrawal/{agentId}/{createdAt}/{page}/{size}")
    public Result cashWithdrawal(@PathVariable String agentId, @PathVariable String createdAt, @PathVariable int page, @PathVariable int size) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        //判断是否登录
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        return new Result(StatusCode.SUCCESS_QUERY, JSON.parseArray(ordersClient.thirdFindSubOrdersByAgentIdAndCreatedAt(agentId, createdAt, page, size)));
    }

    /**
     * 允许代理商提现
     *
     * @param agentId
     * @param settlementDate
     * @return
     */
    @PutMapping("cashWithdrawal/{agentId}/{settlementDate}")
    public Result updateCashWithdrawal(@PathVariable String agentId, @PathVariable String settlementDate) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        //判断是否登录
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        ordersClient.thirdUpdateSettlementStatus("1", agentId, settlementDate);
        return new Result(StatusCode.SUCCESS);
    }

    /**
     * 检查实体类是否存在
     *
     * @param agentInDb
     * @return
     */
    public String checkPojo(Agent agentInDb) {
        if (agentInDb == null) {
            return ("该代理商不存在");
        }
        if (agentInDb.getDeletedAt() != null) {
            return ("该代理商已被删除");
        }
        return "";
    }
}
